package com.jiangjiang.eshop.schedule.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangjiang.eshop.schedule.dao.GoodsStockMapper;
import com.jiangjiang.eshop.schedule.domain.GoodsStockEntity;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName GoodsStockService
 * @Description 调度系统商品库存service组件
 * @Author jhw
 * @Date 2021/8/30 22:34
 * @Version 1.0
 **/
@Service
public class ScheduleGoodsStockService extends ServiceImpl<GoodsStockMapper, GoodsStockEntity> {
    /***
     * 根据sku id集合查询商品库存数据
     * @param skuIds sku id 集合数据
     * @return
     */
    public List<GoodsStockEntity> queryBySkuIds(Set<Long> skuIds) {
        LambdaQueryWrapper<GoodsStockEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.in(GoodsStockEntity::getGoodsSkuId, skuIds);

        List<GoodsStockEntity> entities = this.list(wrapper);
        // 对于没有库存记录的数据需要进行新增
        Set<Long> existSkuIds = entities.stream().map(GoodsStockEntity::getGoodsSkuId).collect(Collectors.toSet());
        List<GoodsStockEntity> needSaveEntities = skuIds.stream().filter(id -> !existSkuIds.contains(id)).map(id -> GoodsStockEntity.builder()
                .goodsSkuId(id)
                .availableStockQuantity(0L)
                .lockedStockQuantity(0L)
                .outputStockQuantity(0L)
                .build()).collect(Collectors.toList());

        this.saveBatch(needSaveEntities);
        entities.addAll(needSaveEntities);

        return entities;
    }
}
